import type { ElTable } from 'element-plus'

// import type { TableColumnCtx } from 'element-plus/es/components/table/src/table-column/defaults'

// 列表控件的属性 
import type { 
  IGridMeta,
  // IGridTable,
  // IGridProps,
  // IGridItem,
  IGridSelection
} from '../map'

export interface IRow {
  [key: string | number]: any
}

/**
 * 列表的单选和多选的事件
 * @param selection 选择的记录
 * @param gridMeta  使用 idName， 主键字段名
 * @param gridRef el-table 的 $ref
 */
export default function choiceManage(
  selection: IGridSelection,
  // idName: string,
  gridMeta: IGridMeta,
  gridRef: ElTable
) {
  // 是否单选触发
  let isCurrenting = false
  // 是否多选触发
  let isMoring = false

  // 单选
  const currentChange = (row: IRow) => {
    if (isMoring) return // 多选代码触发
    if (!row) return // 清空

    if (gridRef.value) {
      isCurrenting = true
      gridRef.value.clearSelection() // 清空多选
      gridRef.value.toggleRowSelection(row) // 设置复选框
      gridRef.value.setCurrentRow(row) // 设置单选
      // 记录
      selection.dataId = row[gridMeta.idName]
      selection.dataIds = [ row[gridMeta.idName] ]
      selection.row = row
      selection.rows = [ row ]

      isCurrenting = false
    }
  }

  // 多选
  const selectionChange = (rows: Array<IRow>) => {
    if (isCurrenting) return
    // 记录
    if (typeof selection.dataIds === 'undefined') {
      selection.dataIds = []
    }
    selection.dataIds.length = 0 // 清空
    // 设置多选
    rows.forEach((item: IRow) => {
      if (typeof item !== 'undefined' && item !== null) {
        selection.dataIds.push(item[gridMeta.idName])
      }
    })
    selection.rows = rows
    // 设置单选
    switch (rows.length) {
      case 0:
        // 清掉单选
        gridRef.value.setCurrentRow()
        selection.dataId = ''
        selection.row = {}
        break
      case 1:
        isMoring = true
        // 设置新单选
        gridRef.value.setCurrentRow(rows[0])
        isMoring = false
        selection.row = rows[0]
        selection.dataId = rows[0][gridMeta.idName]
        break
      default:
        // 清掉单选
        gridRef.value.setCurrentRow()
        selection.row = rows[rows.length - 1]
        selection.dataId = selection.row[gridMeta.idName]
    }
  }

  return {
    currentChange, // 单选
    selectionChange // 多选
  }
}